package dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.sql.DataSource;

import org.springframework.stereotype.Repository;

import vo.Customer;
import dao.CustomerDao;



@Repository(value = "customerDaoImpl")
public class CustomerDaoImpl implements CustomerDao{
//	@Resource(name="dataSource1")
//	private DataSource ds;

	@PersistenceContext(name="un")
	private EntityManager manager;


	@Override
	public int addCustomer(Customer c) {
	
		manager.persist(c);

		return 1;
	}

	@Override
	public Customer findCustomerByName(String name) {
		
		String jpql = "select c from Customer c where c.name=:name";
		Query query=manager.createQuery(jpql);
        query.setParameter("name",name);
        List<Customer> cl =query.getResultList();
        if(cl.size()!=0){
			Customer customer = cl.get(0);
			return customer;
		}
		else return null;
	}

	@Override
	public Customer findCustomerByNameAndPwd(String name, String pwd) {

		String jpql = "select c from Customer c where c.name=:name and c.pwd=:pwd";
		Query query=manager.createQuery(jpql);
        query.setParameter("name",name);
        query.setParameter("pwd",pwd);
        List<Customer> cl =query.getResultList();
		if(cl.size()!=0){
			Customer customer = cl.get(0);
			return customer;
		}
		else return null;
	}
	
	

//	@Override
//	public int deleteCustomerById(String id) {
//		EntityManager manager = factory.createEntityManager();
//		EntityTransaction tx = manager.getTransaction();
//		tx.begin();
//		Customer customer = manager.find(Customer.class, id);
//		manager.remove(customer);
//		tx.commit();
//		manager.close();
//		return 1;
//	}
//
//	@Override
//	public int updateCustomerById(Customer c) {
//		EntityManager manager = factory.createEntityManager();
//		EntityTransaction tx = manager.getTransaction();
//		tx.begin();
//		Customer customer = manager.find(Customer.class, c.getId());
//		customer = c;
//		manager.merge(customer);
//		tx.commit();
//		manager.close();
//		return 1;
//	}
//	
	


}
